#include "usermanagement.h"
#include "ui_usermanagement.h"
Q_GLOBAL_STATIC(UserManageMent,theInstance);
UserManageMent::UserManageMent(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::UserManageMent)
{
    ui->setupUi(this);
    this->setWindowTitle("用户管理界面");
    this->setWindowIcon(QIcon(":res/res/UserManagement.ico"));
    getUserInformation(UserInformation);
    initlineEditAccountNumber();
    initAddorChangeLineEdit();
    setUserTableWidgetList(0);
    setTipLineEdit();
    QObject::connect(this,&UserManageMent::deleteUserInfomation,this,&UserManageMent::upDataTheTable);
    QObject::connect(RegisteredUserInformation::instance(),&RegisteredUserInformation::upUserData,this,&UserManageMent::upDataUserInformation);
     QObject::connect(this,&UserManageMent::addUserInfomation,this,&UserManageMent::upDataUserInformation);
    QObject::connect(this,&UserManageMent::saveUserInformation,this,&UserManageMent::upDataTheTable);
    QObject::connect(this,&UserManageMent::changeUserInfomation,this,&UserManageMent::upDataTheTable);

}

UserManageMent *UserManageMent::instance()
{
    return theInstance;
}

UserManageMent::~UserManageMent()
{
    delete ui;
}

void UserManageMent::on_pushButton_Back_clicked()
{
    this->close();
}


void UserManageMent::on_pushButtonCheckAccount_clicked()
{
setTableDisplay();
}














bool UserManageMent::getUserInformation(QVector<UserInfo> &Data)
{
    while(!UserInformation.empty())
    {
        UserInformation.pop_back();
    }
    //bool ok=userMysql::instance()->getUserData(Data);
    bool ok=UserMysqlS::instance()->getUserData(Data);
    if(ok)
    {
        qDebug()<<"--------获取用户信息成功------"<<Data.count();
        for(QVector<UserInfo>::Iterator it=Data.begin();it<Data.end();it++)
        {
            qDebug()<<it->id<<" "<<it->accountNumber<<" "<<it->userName<<" "<<it->userType<<" "<<it->userPassword<<endl;
        }
    }
}

void UserManageMent::setUserTableWidgetList(int row,int column)//int row,
{
   if(row>0)
   {
       ui->tableWidgetUserList->setRowCount(row);



   }
    ui->tableWidgetUserList->setColumnCount(column);
    ui->tableWidgetUserList->setHorizontalHeaderLabels(QStringList() << "id" << "账号" << "用户名" << "用户类型"<<"密码");


}

void UserManageMent::initlineEditAccountNumber()
{

    QRegExp regExpA("\\d{11}");//限制输入11位账号
    QRegExpValidator *validatorA = new QRegExpValidator(regExpA, this);
    ui->lineEditAccountNumber->setValidator(validatorA);



}

int UserManageMent::checkAccountNumberIndex(const QString &accountNumber,const QVector<UserInfo> &Data)
{
    int index=-1;
    for(int i=0;i<Data.count();i++)
    {
        if(accountNumber==Data[i].accountNumber)
        {
            index=i;
            break;
        }
    }
    if(index==-1)
    {
        return -1;
    }else
    {
        return index;
    }

}

void UserManageMent::setTableDisplay(bool on_off,const int mode)
{
int Index=0;
if(on_off)
{

Index=mode;


}
else
{

Index =ui->comboBoxCheckMode->currentIndex();//0账号查询 1全部查询;
}

    if(Index)
    {
        int count=UserInformation.count();//获取当前用户数量行数
        //        //ui->tableWidgetUserList->setRowCount(5);
        //        ui->tableWidgetUserList->setColumnCount(count);
        setUserTableWidgetList(count);
        QString temp;
        for(int i=0;i<count;i++)
        {
            for(int j=0;j<5;j++)
            {

                switch(j)
                {
                case 0:
                {
                    temp=QString::number(UserInformation[i].id);
                    QTableWidgetItem * Item=new QTableWidgetItem(temp);
                    ui->tableWidgetUserList->setItem(i,j,Item);
                }
                    break;
                case 1:
                {
                    temp=UserInformation[i].accountNumber;
                    QTableWidgetItem * Item=new QTableWidgetItem(temp);
                    ui->tableWidgetUserList->setItem(i,j,Item);
                }
                    break;
                case 2:
                {
                    temp=UserInformation[i].userName;
                    QTableWidgetItem * Item=new QTableWidgetItem(temp);
                    ui->tableWidgetUserList->setItem(i,j,Item);
                }
                    break;
                case 3:
                {
                    temp=QString::number(UserInformation[i].userType);
                    QTableWidgetItem * Item=new QTableWidgetItem(temp);
                    ui->tableWidgetUserList->setItem(i,j,Item);
                }
                    break;
                case 4:
                {
                    temp=UserInformation[i].userPassword;
                    QTableWidgetItem * Item=new QTableWidgetItem(temp);
                    ui->tableWidgetUserList->setItem(i,j,Item);
                }
                    break;
                default:
                    break;

                }


            }
        }
    }
    else
    {

        QString accountNumber=ui->lineEditAccountNumber->text();
        int index1=checkAccountNumberIndex(accountNumber,UserInformation);
        if(-1!=index1)
        {
            QString temp;//中间变量

            setUserTableWidgetList(1);
            for(int j=0,i=index1;j<5;j++)
            {

                switch(j)
                {
                case 0:
                {
                    temp=QString::number(UserInformation[i].id);
                    QTableWidgetItem * Item=new QTableWidgetItem(temp);
                    ui->tableWidgetUserList->setItem(0,j,Item);
                }
                    break;
                case 1:
                {
                    temp=UserInformation[i].accountNumber;
                    QTableWidgetItem * Item=new QTableWidgetItem(temp);
                    ui->tableWidgetUserList->setItem(0,j,Item);
                }
                    break;
                case 2:
                {
                    temp=UserInformation[i].userName;
                    QTableWidgetItem * Item=new QTableWidgetItem(temp);
                    ui->tableWidgetUserList->setItem(0,j,Item);
                }
                    break;
                case 3:
                {
                    temp=QString::number(UserInformation[i].userType);
                    QTableWidgetItem * Item=new QTableWidgetItem(temp);
                    ui->tableWidgetUserList->setItem(0,j,Item);
                }
                    break;
                case 4:
                {
                    temp=UserInformation[i].userPassword;
                    QTableWidgetItem * Item=new QTableWidgetItem(temp);
                    ui->tableWidgetUserList->setItem(0,j,Item);
                }
                    break;
                default:
                    break;

                }


            }




        }
        else{

            QMessageBox::information(this,"Tip","该账号不存在！");


        }


    }


}

void UserManageMent::clearTable()
{

// 获取行列总数
    int rowCount = ui->tableWidgetUserList->rowCount();
    int colCount = ui->tableWidgetUserList->columnCount();

    // 遍历每个单元格
    for (int row = 0; row < rowCount; ++row) {
        for (int col = 0; col < colCount; ++col) {
            // 取出并删除 Item
            QTableWidgetItem* item = ui->tableWidgetUserList->takeItem(row, col);
            delete item; // 释放内存
        }
    }





}

void UserManageMent::initAddorChangeLineEdit()
{
    QRegExp regExp1("\\d{11}");//限制输入11位账号
    QRegExp regExp2("\\d{6}");
    QRegExpValidator *validator1 = new QRegExpValidator(regExp1, this);
    QRegExpValidator *validator2 = new QRegExpValidator(regExp2, this);
    ui->lineEditAccountNumber_AC->setValidator(validator1);
    ui->lineEditUserPassword->setValidator(validator2);
}

void UserManageMent::setTipLineEdit()
{
    ui->lineEditAccountNumber_AC->setPlaceholderText("请输入账号");
    ui->lineEditUserName->setPlaceholderText("请输入用户名");
    ui->lineEditUserPassword->setPlaceholderText("请输入密码");
    ui->lineEditUserPassword->setEchoMode(QLineEdit::Password);//密码模式
}

int UserManageMent::checkUserIsExist( UserInfo &Data,QVector<UserInfo>&DataSet)
{

    getUserInformation(DataSet);//更新数据
    int id=-1;
    for(int i=0;i<DataSet.count();i++)
    {
        if(Data.accountNumber==DataSet[i].accountNumber&&Data.userName==DataSet[i].userName&&Data.userPassword==DataSet[i].userPassword)
        {
            id=DataSet[i].id;
            break;
        }
    }
    if(id==-1)
    {
        return -1;
    }
    else
    {
        return id;
    }
}

void UserManageMent::on_pushButtonClear_clicked()
{
ui->lineEditAccountNumber->clear();
}


void UserManageMent::on_pushButtonDeleteAccount_clicked()
{
    QMessageBox::StandardButton reply = QMessageBox::question(
                this,
                tr("Delete"),
                tr("确定要删除吗？"),
                QMessageBox::Yes | QMessageBox::No,
                QMessageBox::No  // 默认选中No
                );
    if (reply == QMessageBox::Yes)
    {
        //首先获取当前选中的行号
        int currentRow=ui->tableWidgetUserList->currentRow();
        if(currentRow==-1)
        {
           // QMessageBox::question(this, "Tip", "没有选择用户",QMessageBox::Yes);
            QMessageBox::information(this,"Tip",   "没有选择用户" );

        }
        else
        {

            qDebug()<<"currentRow:"<<currentRow;
            //获取当前行的id
            QTableWidgetItem *item = ui->tableWidgetUserList->item(currentRow, 0);
//            //获取当前行的AccountNumber
//            QTableWidgetItem *item = ui->tableWidgetUserList->item(currentRow, 1);

            if(item!=nullptr)
            {
             QString currentId=item->text();
             int id=currentId.toInt();

             qDebug()<<"删除！"<<id;
             //bool ok=userMysql::instance()->deleteUserData(id);
             bool ok=UserMysqlS::instance()->deleteUserData(id);
             if(ok)
             {

                 QMessageBox::information(this,"tip",   "删除用户成功" );// 可选按钮     ,QMessageBox::Yes | QMessageBox::No
                 //刷新数据

//                 LogRecord::instance()->writeLogRecord("删除账号","","");
                 emit deleteUserInfomation(ok);

             }
             // 执行操作

            }
            else
            {
            qDebug()<<"未找到用户信息";
            }


        }
        //QString goalAccountNumber=ui->tableWidgetUserList->


    }
    else if(reply==QMessageBox::No){
        qDebug()<<"取消！";
    }


}

void UserManageMent::upDataTheTable(const bool &ok)
{
    if(ok)
    {


//        ui->tableWidgetUserList->clear();          // 清除所有内容（含表头）
//        ui->tableWidgetUserList->setRowCount(0);   // 确保行数为0（可选）
//        ui->tableWidgetUserList->setColumnCount(0);// 确保列数为0（可选）
        clearTable();
        setUserTableWidgetList(0);
        //清空原先的UserInformation

        getUserInformation(UserInformation);//首先更新用户信息
        setTableDisplay(true);


    }

}

void UserManageMent::upDataUserInformation(const bool &ok)
{
    if(ok)
    {
        getUserInformation(UserInformation);
    }
}


void UserManageMent::on_pushButtonAddUser_clicked()
{

UserInfo Data;
Data.accountNumber=ui->lineEditAccountNumber_AC->text();
Data.userType=0;
Data.userName=ui->lineEditUserName->text();
Data.userPassword=ui->lineEditUserPassword->text();
//bool ok= userMysql::instance()->saveUserData(Data);
bool ok= UserMysqlS::instance()->saveUserData(Data);

qDebug()<<"ok------------->"<<ok;
if(ok)
{
    emit addUserInfomation(ok);

//    emit saveUserInformation(ok);
//    qDebug()<<"emit--------->";
}

}

void UserManageMent::on_pushButtonChange_clicked()
{

UserInfo Data;
// 设置提示文本
UserInfo Temp;
Temp.accountNumber=ui->lineEditAccountNumber_AC->text();
Temp.userName=ui->lineEditUserName->text();
Temp.userPassword=ui->lineEditUserPassword->text();
int id=checkUserIsExist(Temp,UserInformation);
//查询用户是否存在
QString text;
QString text2;
if(id!=-1)
{

//    bool ok2;
    bool ok;
    bool ok1;
    do {
        text= QInputDialog::getText(this,"Tip","请输入新密码（6位密码）！",QLineEdit::Password,"",&ok);

        // 用户点击取消则退出循环
        if (!ok) break;

        // 检查位数
        if (text.length() !=6) {
            QMessageBox::warning(this, "错误", "密码必须为6位！");
        }
    } while (!ok||text.length()!=6);//false
 QMessageBox::information(this,"Tip","第一次输入完成！");
 do {
     text2= QInputDialog::getText(this,"Tip","请输入新密码（6位密码）！",QLineEdit::Password,"",&ok1);

     // 用户点击取消则退出循环
     if (!ok) break;

     // 检查位数
     if (text.length() !=6) {
         QMessageBox::warning(this, "错误", "密码必须为6位！");
     }
 } while (!ok||text.length()!=6);//false

 if (ok&&ok1)
 {

     // 处理合法输入
     Data.id=id;
     Data.userName=Temp.userName;
     Data.userPassword=text;
     //int recv=userMysql::instance()->changeUserInformation(Data);
     int recv=UserMysqlS::instance()->changeUserInformation(Data);
     if(recv==1)
     {

         QMessageBox::information(this,"success!","修改用户信息成功！");
         emit changeUserInfomation(true);


     }else if(recv==-1)
     {
         QMessageBox::information(this,"failed!","修改用户信息失败！");
     }
     else
     {
         QMessageBox::information(this,"???!","该账户不存在！");
     }


 }
 else
 {

     QMessageBox::information(this,"Tip","密码不一致，取消修改！");


 }



}
else
{
    QMessageBox::information(this,"Tip","账户不存在");
}












}

